#!/bin/sh

INSTALL_DIR=/data
if [[ ! -e ${INSTALL_DIR} ]];then
    echo "创建安装路径: ${INSTALL_DIR}"
    mkdir ${INSTALL_DIR}
    chmod 777 ${INSTALL_DIR}
fi


systemctl stop firewalld

if [[ ! -e /etc/yum.repos.d/bak ]];then
    mkdir /etc/yum.repos.d/bak
    mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/bak
fi 



if [[ ! -e /mnt/cdrom ]];then
echo "
[local]
name=local
baseurl=file:///mnt/cdrom
gpgcheck=0
enabled=1
" > /etc/yum.repos.d/local.repo

    echo "创建挂载路径: /mnt/cdrom"
    mkdir /mnt/cdrom
    echo "挂载CD"
    mount /dev/cdrom /mnt/cdrom
fi

yum clean all
yum install -y gcc zlib-devel fontconfig



jdkPackageDownloadYUrl="https://mirrors.tuna.tsinghua.edu.cn/Adoptium/17/jdk/x64/linux/OpenJDK17U-jdk_x64_linux_hotspot_17.0.12_7.tar.gz"
jdkPackageFilename="${jdkPackageDownloadYUrl##*/}"
jdkPackagePath="${INSTALL_DIR}/${jdkPackageFilename}"
echo "jdkPackagePath: ${jdkPackagePath}"
if [[ ! -e "${jdkPackagePath}" ]];then
    echo "下载JDK包"
    curl -o "${jdkPackagePath}" "${jdkPackageDownloadYUrl}"
fi

echo "解压..."
tar -zxf "${jdkPackagePath}" -C "${INSTALL_DIR}"


jenkinsPackageDownloadUrl="https://mirrors.tuna.tsinghua.edu.cn/jenkins/war/latest/jenkins.war"
jenkinsPackageFilename="${jenkinsPackageDownloadUrl##*/}"
jenkinsPackagePath="${INSTALL_DIR}/${jenkinsPackageFilename}"
echo "jenkinsPackagePath: ${jenkinsPackagePath}"
if [[ ! -e "${jenkinsPackagePath}" ]];then
    echo "下载Jenkins war包"
    curl -o "${jenkinsPackagePath}" "${jenkinsPackageDownloadUrl}"
fi


echo "添加环境变量"
java_home=${INSTALL_DIR}/`tar -tf ${jdkPackagePath} | head -1 | tr -d '/'`
echo "export JAVA_HOME=${java_home}
export JRE_HOME=\${JAVA_HOME}/jre
export CLASSPATH=.:\${JAVA_HOME}/lib/dt.jar:\${JAVA_HOME}/lib/tools.jar
export PATH=\${JAVA_HOME}/bin:\$PATH" > /etc/profile.d/OpenJDK.sh

source /etc/profile

JENKINS_HOME=/data/jenkins
useradd jenkins -d ${JENKINS_HOME}
if [[ ! -e ${JENKINS_HOME} ]];then
    mkdir -p ${JENKINS_HOME}
fi


# --httpPort=8080
cat > /etc/systemd/system/jenkins.service <<EOF
[Unit]
Description=Jenkins Continuous Integration Server
After=network.target
[Service]
User=jenkins
ExecStart=${JAVA_HOME}/bin/java -jar  ${jenkinsPackagePath} 
Restart=always
[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl start jenkins
systemctl enable jenkins